package com.example.blog.Utils;

import com.example.blog.constant.Contants;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JWTUtils {
    //密钥
    public static String secret = "mVaoZkBtWnYfDaKYNRWzKgN3olwC4KAo/DhG7uRw3Ts=";
    //过期时间
    public static long expirationTime = 60 * 60 * 24 * 1000;
    //生成安全密钥
    private static SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
    //生成密钥
    public static String genJwt(Map<String,Object> claim) {
        //签名算法
        String jwt = Jwts.builder()
                .setClaims(claim)//自定义内容
                .setIssuedAt(new Date())//设置签发时间
                .setExpiration(new Date(System.currentTimeMillis()+expirationTime))//过期时间
                .signWith(secretKey)
                .compact();
        return jwt;
    }
    //验证密钥
    public static Claims parseJwt(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(secretKey).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.error("解析token失败, token:{}", token);
            return null;
        }
        return claims;
    }
    public static Integer getUserIdBytoken(String token){
       Claims claims = parseJwt(token);
       if(claims != null){
           Integer userId = (Integer) claims.get(Contants.TOKEN_ID);
           return userId;
       }
       return null;
    }

}
